package com.max.common.oauth.oauth10.servlet;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.max.common.oauth.oauth10.OAuthApiBase;
import com.max.common.oauth.oauth10.OAuthToken;
import com.max.common.oauth.oauth10.impl.OAuthApiSinaMicroBlog;
import com.max.common.oauth.oauth10.impl.OAuthApiTencentMicroBlog;

@SuppressWarnings("serial")
public class OAuth10Servlet extends HttpServlet 
{

	@Override
	public void init(ServletConfig config) throws ServletException 
	{
		super.init(config);
	}

	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		OutputStream os = response.getOutputStream();
		String path = request.getRequestURI();
		OAuthApiBase oAuthApi = null;
		String provider = request.getParameter("provider");
		String callback = request.getParameter("callback");
		
		try
		{
			if(provider == null && callback == null)
			{
				String html = "<a href=\""+path+"?provider=microblog_sina\">新浪微博 </a>" +
						  "|<a href=\""+path+"?provider=microblog_tencent\">腾讯微博 </a>";
				os.write(html.getBytes());
				os.close();
				return;
			}
			
			
			if(provider != null && provider.equals("microblog_sina"))
				oAuthApi = new OAuthApiSinaMicroBlog();
			else if(provider != null && provider.equals("microblog_tencent"))
				oAuthApi = new OAuthApiTencentMicroBlog();
			oAuthApi.setCallback(request.getRequestURL()+"?callback=1&provider="+provider);
			
			
			if(callback == null || !callback.equals("1"))
			{
				OAuthToken request_token = oAuthApi.requestToken();
				request.getSession().setAttribute("request_token",request_token);
				response.sendRedirect(oAuthApi.getConsumer().getProvider().getAuthorizationURL() 
					+ "?oauth_token=" + request_token.getOauth_token());
				return;
			}
			else
			{
				OAuthToken request_token = (OAuthToken)request.getSession().getAttribute("request_token");
				String verifier=request.getParameter("oauth_verifier");
				oAuthApi.setOauth_verifier(verifier);
				OAuthToken access_token = oAuthApi.accessToken(request_token);
				request.getSession().setAttribute("access_token",access_token);
				
				os.write(access_token.toString().getBytes());
				os.close();
				return;
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	
	@Override
	public void destroy()
	{
		super.destroy();
	}
}
